﻿using Coldairarrow.Entity.backstage.GrandTickets;
using Coldairarrow.Entity.Backstage.Valickets;
using Coldairarrow.Entity.BTB_StaffUsers;
using Coldairarrow.Entity.Frontstage.Valickets;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.backstage.GrandTickets
{
    public class BS_GrantTicketBusiness : BaseBusiness<BS_GrantTicket>, IBS_GrantTicketBusiness, ITransientDependency
    {
        readonly Operator _operator; 
        public BS_GrantTicketBusiness(IDbAccessor db,Operator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        public async Task<PageResult<GrantTicketDTO>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            Expression<Func<BS_GrantTicket, BTB_StaffUser, GrantTicketDTO>> select = (a, b) => new GrantTicketDTO
            {
                NickName = b.NickName,
                RaleName = b.RealName,
                Sex = b.Sex,
                Phone = b.phone
            };

            select = select.BuildExtendSelectExpre();

            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<BTB_StaffUser>() on a.UserId equals b.id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);


            var where = LinqHelper.True<GrantTicketDTO>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<GrantTicketDTO, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<GrantTicketDTO> GetTheDataAsync(string id)
        {
            Expression<Func<BS_GrantTicket, BTB_StaffUser, GrantTicketDTO>> select = (a, b) => new GrantTicketDTO
            {
                NickName = b.NickName,
                RaleName = b.RealName,
                Sex = b.Sex,
                Phone = b.phone
            };

            select = select.BuildExtendSelectExpre();

            var q = await (from a in GetIQueryable().Where(x => x.Id.Equals(id)).AsExpandable()
                    join b in Db.GetIQueryable<BTB_StaffUser>() on a.UserId equals b.id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b)).ToListAsync();

            return q.FirstOrDefault();
        }

        /// <summary>
        /// 后台——发送优惠券
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SendTicketAsnyc(GrantTicket input)
        {
            //查询优惠券是否存在
            var tmodel = await Db.GetIQueryable<BS_VailTicket>().Where(x => x.Id.Equals(input.ValiTacketId)).ToListAsync();
            if (tmodel.Count > 0 && input.TicketNum > 0)
            {
                List<BS_GrantTicket> mList = new List<BS_GrantTicket>();
                List<BS_UserVailTicket> uLsit = new List<BS_UserVailTicket>();
                foreach (var item in input.UserIds)
                {
                    //判断用户是否存在
                    var suser = await Db.GetIQueryable<BTB_StaffUser>().Where(x => x.id.Equals(item)).ToListAsync();
                    if (suser.Count > 0)
                    {
                        //创建优惠券发送记录
                        BS_GrantTicket model = new BS_GrantTicket();
                        model.Id = IdHelper.GetId();
                        model.CreatorId = _operator.UserId;
                        model.CreateTime = DateTime.Now;
                        model.Deleted = false;
                        model.UserId = suser[0].id;
                        model.ValiTacketId = input.ValiTacketId;
                        model.TicketNum = input.TicketNum;
                        model.TicketTitle = tmodel[0].Ticket_Title;
                        model.TicketMoney = tmodel[0].Ticket_Amount;
                        model.TicketUseMoney = tmodel[0].Ticket_UseMoney;
                        if (tmodel[0].Ticket_EndTime.HasValue)
                        {
                            model.TicketEndTime = (DateTime)tmodel[0].Ticket_EndTime;
                        }
                        else
                        {
                            DateTime theTime = DateTime.Now;
                            if (tmodel[0].Ticket_VailDay.HasValue)
                            {
                                theTime = theTime.AddDays((int)tmodel[0].Ticket_VailDay);
                            }
                            else
                            {
                                theTime = theTime.AddDays(3);
                            }
                            model.TicketEndTime = theTime;
                        }
                        mList.Add(model);

                        //创建用户优惠券
                        for (int k = 0; k < input.TicketNum; k++)
                        {
                            BS_UserVailTicket usModel = new BS_UserVailTicket();
                            usModel.Id = IdHelper.GetId();
                            usModel.CreatorId = _operator.UserId;
                            usModel.CreateTime = DateTime.Now;
                            usModel.Deleted = false;
                            usModel.UserId = suser[0].id;
                            usModel.VailTicketId = tmodel[0].Id;
                            usModel.StartTime = DateTime.Now;
                            usModel.EndTime = model.TicketEndTime;
                            usModel.Ticket_Type = tmodel[0].Ticket_Type;
                            usModel.Ticket_Title = tmodel[0].Ticket_Title;
                            usModel.Ticket_Amount = tmodel[0].Ticket_Amount;
                            usModel.Ticket_BackImg = tmodel[0].Ticket_BackImg;
                            usModel.Ticket_UseMoney = (decimal)tmodel[0].Ticket_UseMoney;
                            usModel.Ticket_Abstract = tmodel[0].Ticket_Abstract;
                            usModel.UseState = 0;
                            usModel.Ticket_KeepOne = tmodel[0].Ticket_KeepOne;
                            usModel.Ticket_ChangePoint = tmodel[0].Ticket_ChangePoint;
                            uLsit.Add(usModel);
                        }
                    }
                    else
                    {
                        throw new BusException("查询用户信息为空创建失败，请确认后重试");
                    }
                }

                if (uLsit.Count > 0)
                {
                    await Db.InsertAsync(uLsit);
                }

                if (mList.Count > 0)
                {
                    await Db.InsertAsync(mList);
                }
            }
            else
            {
                throw new BusException("查询优惠券信息为空创建失败，请确认后重试");
            }
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<SelectDTO>> GetUsersAsnyc()
        {
            List<SelectDTO> uList = new List<SelectDTO>();
            var sList = await (from a in Db.GetIQueryable<BTB_StaffUser>()
                        select new{ 
                            a.id,
                            a.NickName,
                            a.RealName,
                            a.phone                        
                        }).ToListAsync();

            foreach (var item in sList)
            {
                SelectDTO model = new SelectDTO();
                model.Id = item.id;
                string text = item.NickName;
                if (!item.RealName.IsNullOrEmpty())
                {
                    text += "/" + item.RealName;
                }
                text += "/" + item.phone;

                model.Text = text;
                uList.Add(model);
            }

            return uList;
        }

        /// <summary>
        /// 获取优惠券列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<SelectDTO>> GetTickesAsnyc()
        {
            List<SelectDTO> uList = new List<SelectDTO>();
            var sList = await (from a in Db.GetIQueryable<BS_VailTicket>().Where(x => x.Ticket_Type == 1 && x.State == true)
                               select new
                               {
                                   a.Id,
                                   a.Ticket_Title,
                                   a.Ticket_Amount,
                                   a.Ticket_UseMoney
                               }).ToListAsync();

            foreach (var item in sList)
            {
                SelectDTO model = new SelectDTO();
                model.Id = item.Id;
                string text = item.Ticket_Title;
                text += "/" + item.Ticket_UseMoney;
                text += "/" + item.Ticket_Amount;

                model.Text = text;
                uList.Add(model);
            }

            return uList;
        }

        public async Task AddDataAsync(BS_GrantTicket data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(BS_GrantTicket data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            //删除之前优惠券
            foreach (var item in ids)
            {
                var model = GetEntity(item);
                var tList = Db.GetIQueryable<BS_UserVailTicket>().Where(x => x.VailTicketId.Equals(model.ValiTacketId) && x.EndTime == model.TicketEndTime).Take(model.TicketNum).Select(x => x.Id).ToList();
                await Db.DeleteAsync<BS_UserVailTicket>(tList);
            }

            await DeleteAsync(ids);
        }

        #endregion

        #region 私有成员

        #endregion
    }
}